
use std::fs::remove_file;

use clap::Args;
use serde::{Deserialize, Serialize};
use wtask_base::{app::get_wtask_app_dir, cmd::create_file, error::WResult, export::{Local, log_debug}, logs::TIME_FORMAT_FULL};

use crate::{basic::WStatus, task::utils::{func::task_local_simple_check, meta::{TaskMeta, WTASK_DISABLED_FILE}}, utils::AppTrait};


// task status
#[derive(Debug, Clone, Serialize, Deserialize, Args)]
pub struct AppTaskStatus {
    /// 预定义任务ID
    pub(crate) app: String,

    /// 任务的版本，默认最新版
    #[arg(long, default_value = "latest")]
    pub(crate) version: String,
}


impl AppTrait for AppTaskStatus {
    type Status = ();
    type Res = WStatus;

    async fn server_handle_single(self) -> WResult<WStatus> {
        log_debug!("Task status: {self:?}");
        let dir_app = get_wtask_app_dir(&self.app, &self.version)?;
        let task = TaskMeta::new(&dir_app)?;
        let file_disabled = dir_app.join(WTASK_DISABLED_FILE);
        let mut res_log = Vec::new();
        // task status
        let r = if task.enable {
            // disabled
            create_file(&file_disabled, &format!("{} Disabled", Local::now().format(TIME_FORMAT_FULL)))?;
            true
        } else {
            // enabled
            match task_local_simple_check(&dir_app, | _: bool, v | { res_log.push(v); }) {
                Ok(false) => {
                    let _ = remove_file(file_disabled);
                    true
                },
                Ok(true) => {
                    res_log.push(format!("Task Check Error: {}@{}", self.app, self.version));
                    false
                },
                Err(e) => {
                    res_log.push(format!("Task Check Error: {}@{} {}", self.app, self.version, e));
                    false
                }
            }
        };
        if r {
            res_log.push(format!(
                "Task Status Change Success, Status Now: {}@{} {}",
                task.id,
                task.version,
                if task.enable { "Disabled" } else { "Enabled" }
            ));
        }
        let res = WStatus::from((r, res_log));
        Ok(res)
    }
}



